import 'package:cbec_app/components/base/privacy_agreement_dialog.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

import '../../utils/GlobalData.dart';

class StartPrivacyPage extends StatefulWidget {
  const StartPrivacyPage({super.key});

  @override
  State<StartPrivacyPage> createState() => _StartPrivacyPageState();
}

class _StartPrivacyPageState extends State<StartPrivacyPage> {
  String currentVersion = '';

  @override
  void initState() {
    super.initState();
    _initializeVersion();
  }

  Future<void> _initializeVersion() async {
    final info = await PackageInfo.fromPlatform();
    setState(() {
      currentVersion = info.version; // 使用 setState 更新版本号
    });
  }

  Future<void> _initializeUmeng() async {
    // 替换为你的友盟 AppKey 和渠道信息

    try {
      await UmengCommonSdk.initCommon(GlobalData.umengAndroidAppkey, GlobalData.umengIosAppkey, 'Umeng');
      debugPrint('友盟初始化成功');
    } catch (e) {
      debugPrint('友盟初始化失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果版本号尚未加载，返回加载状态的占位界面
    if (currentVersion.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }
    // 弹出隐私协议对话框
    bool isShow = !(currentVersion == AppData.versionNo && AppData.isHaveAgree);
    WidgetsBinding.instance.addPostFrameCallback(
      (_) {
        if (isShow) {
          PrivacyAgreementDialog.show(
            context,
            '欢迎使用百大易购',
            true,
            () async {
              AppData.versionNo = currentVersion;
              AppData.isHaveAgree = true;

              // 进行友盟初始化
              await _initializeUmeng();

              // 跳转到主页面
              Get.offNamed(Routes.splash);
            },
          );
        }
      },
    );
    return const SizedBox();
  }
}
